<?php

namespace app\api\controller;

use app\admin\model\activity\Tuangou;
use app\admin\model\order\Order;
use app\admin\model\SpellOrder;
use app\common\controller\Api;
use app\common\model\Category;
use think\Db;
use think\Exception;

/**
 * 定时接口
 * @ApiInternal
 */
class Crontab extends Api
{
	// 无需登录的接口,*表示全部
	protected $noNeedLogin = '*';

	public function _initialize()
	{
		// 只可以以cli方式执行
		if (!$this->request->isCli())
			//$this->error('Autotask script only work at client!');
		parent::_initialize();
		// 清除错误
		error_reporting(0);

		// 设置永不超时
		set_time_limit(0);
	}
	/**
	 * 定时任务
	 */
	public function goods()
	{
	    $this->addLog("crontab","定时任务开始");
		// 采集商品数据
//        $list = \app\common\model\Category::where(['type'=>'goods_cate','cate_level'=>'3'])
//            ->order('weigh asc')->select();
//        $list=Db::query("SELECT SelfCateId as id from pt_goods where id<=10520 GROUP BY SelfCateId ");
//        if(empty($list)){
//            return false;
//        }
        $cateIds = (new Category())->where(['pid' => ['in',[33,62,192,132,195,196,198]]])->column('id');
        $list = (new Category())->where(['pid' => ['in', $cateIds]])->order('id desc')->select();
        $model = new \app\admin\model\goods\Goods();
        foreach ($list as $ks=>$vs){
            $model->saveTmallGoods($vs['id']);
            sleep(3);
        }
        $this->addLog("crontab","定时任务结束");
	}

    /**
     * @Explain :拉取评论
     * @Date : 2020/9/15 14:24
     * @Author : 河南邦耀网络科技有限公司
     */
	public function comment(){

        $goodsModel = new \app\admin\model\goods\Goods();
        $commModel = new \app\admin\model\Comment();
        $page=1;
        $rowNum=50;
        do {
//            $goods = $goodsModel->field(['goodsid'])->page($page, $rowNum)->order('id desc')->select();
      //      $goods = Db::table('pt_tmall_comment')->field(['itemId as goodsid'])->where(['comment'=>'"余额不足"'])->page($page, $rowNum)->order('id desc')->select();
            if(empty($goods)) break;
            foreach ($goods as $v){
                $commModel->pullTmallGoodsComment($v['goodsid']);
            }
            $page++;
            sleep(1);
        }while(true);
    }
	/**
     * 排行榜
     */
	public function ranking()
    {

    }
    /**
     * 机器人拼团
     */
    public function robot()
    {
        $this->addLog("crontab","机器人定时开始");
        \app\admin\model\spell\Spell::crontab();
        $this->addLog("crontab","机器人定时开始");
        exit;
    }
    /**
     * 订单自动收货
     */
    public function orderAuto()
    {
        $this->addLog("crontab","自动收货定时开始");
        \app\admin\model\SpellOrder::crontab();
        $this->addLog("crontab","自动收货定时开始");
        exit;
    }
    /**
     * 代理升级
     */
    public function agentUp()
    {
        $this->addLog("crontab","代理升级定时开始");
        \app\admin\model\agent\Valid::crontab();
        $this->addLog("crontab","代理升级定时开始");
        exit;
    }

    public function setSellCount(){
        set_time_limit(0);
        $page=1;
        $goodsModel= new \app\admin\model\goods\Goods();
        do{
            $goods=$goodsModel->field(['id,sales'])->order('id asc')->page($page,100)->select();
            if(empty($goods)) break;
            foreach ($goods as $row){
                $goodsModel->save(['sellCount'=>$this->parseSellCount($row['sales'])],['id'=>$row['id']]);
            }
            echo '已处理'.($page*100).'条';
            echo    "/r/n";
            ob_flush();
            $page++;
        }while(true);
        echo '已完成';
    }

    public function setOrderInvalid (){
        $pinggoodsovertime = \think\config::get("site.pinggoodsovertime");
        $overtime = time() - $pinggoodsovertime*60;
        $res=Db::query("UPDATE `pt_spell_order` SET orderStatus=0,updatetime=".time()." WHERE payStatus=0 AND orderStatus=1 AND createtime<".$overtime);
    }

    public function orderRebate(){
        try {
            //拼团返佣
            $queue=Db::table('pt_rebate_queue')->where(['status'=>0])->order('ctime asc')->select();
            foreach ($queue as $row){
                Db::startTrans();
                \app\admin\model\rebate\Rebate::confirmRebate($row['orderId']);
                Db::table('pt_rebate_queue')->where(['id'=>$row['id']])->update(['status'=>1,'rebate_time'=>date('Y-m-d H:i:s')]);
                Db::commit();
                sleep(1);
            }
        }catch (Exception $exception){
            dump($exception->getMessage());
            Db::rollback();
        }
    }

    private function parseSellCount($str){
        $num=$str;
        if(preg_match('/\d+/',$str,$arr)){
            $num=$arr[0];
        }
        if(strpos($str,'万')){
            $num*=10000;
        }
        return $num;
    }
    public function setSales(){
        set_time_limit(0);
        $page=1;
        $goodsModel= new \app\admin\model\goods\Goods();
        do{
            $goods=$goodsModel->field(['id,sales'])->order('id asc')->page($page,100)->select();
            if(empty($goods)) break;
            foreach ($goods as $row){
                if(preg_match('/^(\d)*$/',$row['sales'],$arr)){
                    $row['sales']='月销'.$arr[0].'笔';
                }
                $goodsModel->save(['sales'=>$row['sales']],['id'=>$row['id']]);
            }
            echo '已处理'.($page*100).'条';
            echo  "/r/n";
            ob_flush();
            $page++;
        }while(true);
        echo '已完成';
    }

    public function setGoodsContent(){
        $goodsModel= new \app\admin\model\goods\Goods();


        Db::name('goods')
            ->where('content', '=', 'null')
            ->chunk(100, function ($list) use ($goodsModel) {
                foreach($list as $row){
                    $item=$goodsModel->getItem($row['goodsid']);
                    $goodsModel->saveItemContent($row['goodsid'],$item);
                }
            });
    }

    /**
     * @Explain :拉取单条评论
     * @Date : 2020/9/15 14:24
     * @Author : 河南邦耀网络科技有限公司
     */
    public function oneComment(){
        $goodsId='628993216729';
        $commModel = new \app\admin\model\Comment();
        $commModel->pullTmallGoodsComment($goodsId);
    }

    /*
     * 活动开始
     */
    public function promotionStart(){

        //自动开始活动
        $res=Tuangou::update(['status'=>1],['status'=>0,'start_time'=>['<=',time()]]);

        //设置自动完成
        $promInfo=Tuangou::where(['status'=>1])->where('end_time','<',time()-180)->find();
        if(empty($promInfo)) return 1;
        $days = \think\config::get("site.saleDays");
        $finishtime=time()+$days*86400;
        $res=SpellOrder::update(['orderStatus'=>11,'finishtime'=>$finishtime],['actid'=>$promInfo['id']]);
        Tuangou::update(['pnum'=>$promInfo['zcount'],'status'=>2,'finish_time'=>time()],['id'=>$promInfo['id'],'status'=>1]);
        $list=SpellOrder::all(['actid'=>$promInfo['id']]);
        foreach ($list as $row){
//            \app\common\library\Sms::otherSend([
//                "uid"=>$row['uid'],
//                "type"=>10,
//                "days"=>$days,
//                "income"=>bcmul($row['payPrice'],$promInfo['rate']*0.01,2),
//            ]);
        }

    }


}
